<?php

namespace common\models;

use Yii;
use yii\base\Exception;

/**
 *
 * Class Sign
 * @package common\models
 */
class Sign
{
    private $timeout = 300;

    private $sign = "rewoitOIJIS344ADerklwe09ri09";

    public function checkParams()
    {
        $params = Yii::$app->request->post();

        if (empty($params)) {
            return true;
        }
        if (YII_DEBUG) {
            return true;
        }

        if (!isset($params['sign']) || empty($params['sign'])) {
            throw new Exception("无效签名，请升级APP");
        }

        if (!isset($params['t']) || empty($params['t'])) {
            throw new Exception("无效签名，请升级APP");
        }
        # 校验时间
        $this->isInvaild($params['t']);

        $sign = $this->verifySign($params);

        if ($sign != strtoupper($params['sign'])) {
            throw new Exception("sign is error");
        }
    }

    # 可变性 时效性 唯一性 完整性
    public function verifySign($params = [])
    {
        unset($params['sign']);
        $signData = $params;

        ksort($signData);

        $signStr = http_build_query($signData);

        return strtoupper(md5($signStr . $this->sign));
    }

    private function isInvaild($time = 0)
    {
        if (empty($time)) {
            throw new Exception("sign no time");
        }

        if (YII_DEBUG) {
            $this->timeout = 5000;
        }

        if (time() - $time > $this->timeout) {
            throw new Exception("The request is invalid");
        }
    }
}
